package cn.bluedot.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.bluedot.model.User;
/**
 * 请求拦截器   在用户为登录的情况下拦截所有的请求 跳转到登录界面
 * @author hxp
 * 2019年5月9日 下午9:11:09
 */
public class RequestInterceptor implements HandlerInterceptor {
    public static final String[] IGNORE_URL = {"/login.html", "/login"};
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    /**
     * 此方法在Controller调用之前执行 返回false时结束整个请求 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        boolean  flag = false;
        String requestUrl = request.getServletPath();
        for(String url : IGNORE_URL) {
            if(requestUrl.contains(url)) {
                flag = true;
                break;
            }
        }
        
        if(!flag) {
            User  user = (User)request.getSession().getAttribute("user");
            if(user == null) {
                request.setAttribute("message", "请先登录再访问网站！ ");
                //request.getRequestDispatcher("login.html").forward(request, response);
                response.sendRedirect("/IntelligentPigBreedingSystem/login.html");
                return flag;
            }else {
                flag = true;
            }
        }
        return flag;
    }

}
